package com.sj.filter;

import com.sj.common.exception.CustomException;
import com.sj.common.lang.Const;
import com.sj.security.LoginFailHandler;
import com.sj.utils.MineUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-03-11
 * Time: 上午 9:10
 * Description: 验证码过滤器
 *
 * @author xiaoqi
 * @since 2022-03-11
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private MineUtils mineUtils;

    @Autowired
    private LoginFailHandler loginFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        // 如果是登录请求，就拦截，并且判断验证码是否正确
        if (requestURI.contains(Const.LOGIN_URL) && method.equalsIgnoreCase(Const.POST_METHOD)) {
            try {
                mineUtils.checkCaptcha(request);
            } catch (CustomException e) {
                // 验证码错误 抛出异常给登陆失败处理器
                loginFailHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        // 验证码正确 或 其他请求 正常放行
        filterChain.doFilter(request, response);
    }

}